<template>
  <div>
    <el-dialog
      modal-class="cailiao-dialog"
      v-model="_isOpen"
      width="1200"
      :title="'根据商品添加'"
      align-center
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <template #header>
        <h4>
          {{
            (props.optionInfo.type === "zhu" && _project?.mainProductShowType === 2) ||
            (props.optionInfo.type === "fu" && _project?.auxiliaryProductShowType === 2)
              ? "根据条件组合添加"
              : "根据商品添加"
          }}
        </h4>
      </template>
      <template #default>
        <header>
          <div class="left">
            <h3 class="mr40">
              定额{{ props.optionInfo.type === "zhu" ? "主材" : "辅材" }}报价：<span
                >¥{{ _detail.quoteMoney || getTotalPrice() || "-" }}</span
              >
            </h3>

            <!-- mainProductShowType auxiliaryProductShowType :1-具体商品 2-条件组合 -->
            <el-form
              v-if="
                (props.optionInfo.type === 'zhu' && _project?.mainProductShowType === 2) ||
                (props.optionInfo.type === 'fu' && _project?.auxiliaryProductShowType === 2)
              "
              :model="form"
              ref="formRef"
              :inline="true"
              label-width="auto"
              style="max-width: 600px"
            >
              <el-form-item
                v-if="props.optionInfo.type === 'zhu'"
                prop="limitProductNum"
                label="主材数量"
                :rules="{ required: true, message: '请输入', trigger: ['blur'] }"
              >
                <el-input
                  disabled
                  v-model="form.limitProductNum"
                  oninput="value=value.replace(/[^0-9]/g, '')"
                  style="width: 100px"
                />
              </el-form-item>
              <el-form-item
                v-else
                prop="limitProductNum"
                label="辅材数量"
                :rules="{ required: true, message: '请输入', trigger: ['blur'] }"
              >
                <el-input
                  disabled
                  v-model="form.limitProductNum"
                  oninput="value=value.replace(/[^0-9]/g, '')"
                  style="width: 100px"
                />
              </el-form-item>
              <el-form-item
                prop="limitProductMoney"
                label="限制金额"
                :rules="{ required: false, message: '请输入', trigger: ['blur'] }"
              >
                <el-input
                  disabled
                  v-model="form.limitProductMoney"
                  oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                  style="width: 100px"
                >
                  <template #prefix>¥</template>
                </el-input>
              </el-form-item>
            </el-form>
          </div>
          <div
            class="right"
            v-if="
              ((props.optionInfo.type === 'zhu' && _project?.mainProductShowType === 2) ||
                (props.optionInfo.type === 'fu' && _project?.auxiliaryProductShowType === 2)) &&
              optionInfo.actionType === 'edit'
            "
          >
            <el-button
              type="primary"
              @click="
                () => {
                  conditionIsOpen = true;
                  optionInfoCondition = {
                    budgetId: _project.budgetId,
                    contentId: _project.contentId,
                    productType: optionInfo.type === 'zhu' ? 1 : 2,
                    detail: _detail,
                    project: _project
                  };
                }
              "
              >添加材料</el-button
            >
          </div>
        </header>

        <div class="table-wrap">
          <el-table
            v-if="tableData.length > 0"
            ref="tableRef"
            class="jzt-table"
            :data="tableData"
            stripe
            style="width: 100%; height: 500px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              v-if="isAllowTableSelect"
              type="selection"
              fixed
              width="40"
              :selectable="() => optionInfo.actionType === 'edit'"
            />
            <el-table-column label="序号" fixed type="index" width="40" />
            <el-table-column prop="productAliasName" show-overflow-tooltip label="材料名称">
              <template #default="scope">
                <p class="text-break">{{ scope.row.productAliasName || "-" }}</p>
                <el-button v-if="scope.row.isContOut === 1" class="pl0" type="success" link>增项</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="skuSpecification" show-overflow-tooltip label="规格" width="140" />
            <el-table-column prop="productUnit" show-overflow-tooltip label="单位" width="80">
              <template #default="scope">
                {{ useCodeArrStore().getDictName("shop_unit", scope.row.productUnit) }}
                <!-- {{ scope.row.productUnit || "-" }}  -->
              </template>
            </el-table-column>
            <el-table-column prop="quoteUnitPrice" show-overflow-tooltip label="单价报价" width="120">
              <template #default="scope">
                <p v-if="optionInfo.dialogType === 'ys'">¥{{ scope.row.quoteUnitPrice || "-" }}</p>
                <p v-if="optionInfo.dialogType === 'de'">¥{{ scope.row.costUnitPrice || "-" }}</p>
                <el-button
                  v-if="
                    Number(scope.row.productNum) - Number(scope.row._productNum) > 0 &&
                    !(isAnySelectAny && optionInfo.currTempObj.budgetType === 2)
                  "
                  class="pl0"
                  type="success"
                  link
                >
                  +{{ (Number(scope.row.productNum) - Number(scope.row._productNum)) * Number(scope.row.quoteUnitPrice) }} (增配)
                </el-button>
                <el-button
                  v-if="
                    Number(scope.row.productNum) - Number(scope.row._productNum) < 0 &&
                    !(isAnySelectAny && optionInfo.currTempObj.budgetType === 2)
                  "
                  class="pl0"
                  type="danger"
                  link
                >
                  {{ (Number(scope.row.productNum) - Number(scope.row._productNum)) * Number(scope.row.quoteUnitPrice) }} (减配)
                </el-button>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="warrantyTime" label="商品质保日期" width="110"> </el-table-column> -->
            <el-table-column prop="productNum" label="数量" width="180">
              <template #header="scope">
                <p>
                  数量
                  <template v-if="isAnySelectAny">
                    （<span style="color: #3d3d3d">限制数量：{{ _detail?.productCheckedNum }}</span> ）
                  </template>
                </p>
              </template>
              <template #default="scope">
                <p v-if="optionInfo.actionType === 'view'">{{ scope.row.productNum || "-" }}</p>
                <el-input
                  v-else
                  class="mr12"
                  v-model="scope.row.productNum"
                  oninput="value=value.replace(/[^0-9]/g, '')"
                  style="width: 100px"
                  @change="changeNUM(scope.row)"
                ></el-input>
                <b
                  v-if="
                    Number(scope.row.productNum) - Number(scope.row._productNum) > 0 &&
                    !(isAnySelectAny && optionInfo.currTempObj.budgetType === 2)
                  "
                  style="color: #00b42a"
                >
                  +{{ Number(scope.row.productNum) - Number(scope.row._productNum) }}
                </b>
                <b
                  v-if="
                    Number(scope.row.productNum) - Number(scope.row._productNum) < 0 &&
                    !(isAnySelectAny && optionInfo.currTempObj.budgetType === 2)
                  "
                  style="color: #ff3333"
                >
                  {{ Number(scope.row.productNum) - Number(scope.row._productNum) }}
                </b>
              </template>
            </el-table-column>
            <el-table-column
              prop="incrProductNum"
              label="新增个性化材料"
              width="130"
              v-if="NUMtotal >= _detail?.productCheckedNum && isAnySelectAny && _detail?.productCheckedNum !== 0"
            >
              <template #default="scope">
                <p v-if="optionInfo.actionType === 'view'">{{ scope.row.incrProductNum || "-" }}</p>
                <el-input-number
                  v-else
                  class="jzt-input-number jzt-input-number-hidden"
                  v-model="scope.row.incrProductNum"
                  :min="0"
                  :precision="0"
                  placeholder=""
                  style="width: 90px"
                  controls-position="right"
                />
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="240">
              <template #default="scope">
                <RemarkEditor
                  v-model="scope.row.remark"
                  :isEdit="optionInfo.actionType === 'view' ? false : true"
                  :title="'修改备注'"
                />
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" v-if="optionInfo.actionType === 'edit'" width="80">
              <template #default="scope">
                <el-button type="danger" v-if="scope.row.isContOut === 1" link @click="delContOut(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-empty v-else description="这里暂时什么都没有" />
        </div>
      </template>
      <template #footer v-if="isAnySelectAny || isAllowTableSelect || optionInfo.actionType === 'edit'">
        <div class="dialog-footer">
          <div class="left">
            <template v-if="isAnySelectAny">
              <p>共：{{ tableData.length }}款</p>
              <p class="ml20">
                <span><i class="star">*</i>任选数量：{{ productCheckedNum }}</span>
              </p>
            </template>
            <template v-else-if="isAllowTableSelect">
              <p>共：{{ tableData.length }}款</p>
              <p class="ml20">
                已选中： <span>{{ multipleSelection.length }}</span>
              </p>
            </template>
          </div>
          <div style="flex: auto">
            <el-button type="info" @click="cancelClick">取消</el-button>
            <el-button
              type="primary"
              v-if="optionInfo.actionType === 'edit'"
              :disabled="tableData.length <= 0"
              :loading="saveLoading"
              @click="confirmClick"
            >
              保存
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 条件内、条件外选商品sku -->
    <conditionSelectProduct
      ref="conditionRef"
      v-model:isOpen="conditionIsOpen"
      :optionInfo="optionInfoCondition"
      @submit="conditionSubmit"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { Search } from "@element-plus/icons-vue";
import conditionSelectProduct from "./conditionSelectProduct.vue";
import { updateQuoteProductNum, saveAddition, deleteAddition } from "@/apis/quote-price/following";
import useCodeArrStore from "@/store/modules/select";
import RemarkEditor from "@/components/RemarkEditor";

const saveLoading = ref(false);
const tableRef = ref();
const emit = defineEmits(["update:isOpen", "submitOk"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        currTempObj: {}, //选中的模板obj
        dialogType: "ys", //ys-预算报价  de-定额模板
        actionType: "edit", //edit view
        type: "zhu", //zhu-主材 fu-辅材
        project: {}, //项目obj，详情页列表当前row
        detail: {}, //明细详情
        getDetailList: null //查询主材、辅材明细列表
      };
    }
  }
});
const conditionRef = ref();
const form = ref({});
const formRef = ref();
const tableData = ref([]);
const conditionIsOpen = ref(false); //条件内、条件外选商品sku
const optionInfoCondition = ref({ budgetId: "", contentId: "", productType: -1, detail: {}, project: {} });
const _detail = ref({});
const _project = ref({}); //项目obj，详情页列表当前row
const productCheckedNum = ref(null);

// 是否允许table勾选(固定商品，并且没有设置几选几)
const isAllowTableSelect = computed(() => {
  const flag =
    props.optionInfo.type === "zhu"
      ? _project.value?.mainProductShowType === 1 && _project.value?.mainCheckType !== 2
      : props.optionInfo.type === "fu"
        ? _project.value?.auxiliaryProductShowType === 1 && _project.value?.auxiliaryCheckType !== 2
        : false;
  return flag;
});

//是否有几选几数量
const isAnySelectAny = computed(() => {
  // 个性化定额quotaType === 7 - 允许显示
  // scope.row.showSign === 0（代表模板自带的）且 _project.quotaType === 1(是通过定额导入的) 且 是固定商品 - 允许显示
  //mainCheckType-主材勾选了几选几   auxiliaryCheckType-辅材勾选了几选几

  const flag =
    props.optionInfo.type === "zhu"
      ? _project.value?.mainProductShowType === 1 && _project.value?.mainCheckType === 2
      : props.optionInfo.type === "fu"
        ? _project.value?.auxiliaryProductShowType === 1 && _project.value?.auxiliaryCheckType === 2
        : false;
  return flag;
  // return (
  //   _project.value.quotaType === 7 ||
  //   _project.value.quotaType === 6 ||
  //   (_project.value.showSign === 0 &&
  //     _project.value.quotaType === 1 &&
  //     ((props.optionInfo.type === "zhu" && _project.value?.mainProductShowType === 1 && _project.value?.mainCheckType === 2) ||
  //       (props.optionInfo.type === "fu" &&
  //         _project.value?.auxiliaryProductShowType === 1 &&
  //         _project.value?.auxiliaryCheckType === 2)))
  // );
});

watch(
  () => props.isOpen,
  val => {
    if (val) {
      //生成临时code-时间戳
      localStorage.setItem("followingObj", JSON.stringify({ _time: new Date().getTime() }));
      console.log("//生成临时code-时间戳==================");
    }
  },
  { deep: true, immediate: false }
);

watch(
  () => props.optionInfo.detail._time,
  val => {
    console.log("传递过来的主材辅材明细", props.optionInfo);

    _detail.value = props.optionInfo.detail;
    //如果没有设置“限制量”，那么默认限制量为0
    if (!_detail.value.productCheckedNum) {
      _detail.value.productCheckedNum = 0;
    }

    _project.value = props.optionInfo.project;

    productCheckedNum.value = props.optionInfo.detail.productCheckedNum;
    tableData.value = props.optionInfo.detail.customerQuotaProductList || props.optionInfo.detail.productVOList || [];
    tableData.value.map(item => {
      const NUM = item.productNum;
      item._productNum = NUM; //原有的数量数据，手动更改数量后，不会对它造成影响
    });
    //初始"数量"求和-NUMtotal
    NUMtotal.value = tableData.value.reduce((prev, cur) => {
      return Number(cur.productNum) + Number(prev);
    }, 0);
    if (
      (props.optionInfo.type === "zhu" && _project.value.mainProductShowType === 2) ||
      (props.optionInfo.type === "fu" && _project.value.auxiliaryProductShowType === 2)
    ) {
      let limitPrice = 0; //更改数量后的限制金额（非增项的数量*报价）
      let limitNum = 0; //更改数量后的限制数量（增项的数量之和）
      tableData.value.map(item => {
        if (item.isContOut === 1) {
          // 增项
        } else {
          //非增项
          limitPrice += Number(item.productNum) * Number(item.quoteUnitPrice);
          limitNum += Number(item.productNum);
        }
      });
      if (limitPrice > _detail.value.limitProductMoney || limitNum > _detail.value.limitProductNum) {
        isExceedsLimit.value = true; //是否超出了金额、数量限制
      } else {
        isExceedsLimit.value = false; //是否超出了金额、数量限制
      }
    } else if (
      (props.optionInfo.type === "zhu" && _project.value.mainProductShowType === 1) ||
      (props.optionInfo.type === "fu" && _project.value.auxiliaryProductShowType === 1)
    ) {
      //固定商品
      nextTick(() => {
        //  回显选中的table行
        const rows = tableData.value.filter(item => item.checked === 1);
        rows.map(row => {
          tableRef.value.toggleRowSelection(row, true);
        });
      });
    }
    form.value = {
      limitProductNum: _detail.value.limitProductNum,
      limitProductMoney: _detail.value.limitProductMoney
    };
  },
  { deep: true, immediate: false }
);

//table多选之后触发的回调，保存选中的行
const multipleSelection = ref([]);
const handleSelectionChange = val => {
  multipleSelection.value = val;

  /**允许显示几选几的时候，判断勾选的行是否超过允许勾选的数量 */
  if (
    _project.value.quotaType === 7 ||
    (_project.value.showSign === 0 &&
      _project.value.quotaType === 1 &&
      ((props.optionInfo.type === "zhu" && _project.value?.mainProductShowType === 1) ||
        (props.optionInfo.type === "fu" && _project.value?.auxiliaryProductShowType === 1)))
  ) {
    // if (
    //   multipleSelection.value.length > 0 &&
    //   (productCheckedNum.value === null || multipleSelection.value.length > productCheckedNum.value)
    // ) {
    //   return ElMessage({
    //     message: "超过了允许勾选的数量",
    //     type: "error"
    //   });
    // }
  }
};

const getTotalPrice = () => {
  let price = 0;
  tableData.value.map(item => {
    price += Number(item.costTotalMoney);
  });
  return price;
};

//删除明细里面的增项
const delContOut = item => {
  deleteAddition({ ...item }).then(async res => {
    if (res.code === 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      //再次查询明细接口
      await props.optionInfo.getDetailList(
        props.optionInfo.project,
        props.optionInfo.type === "zhu" ? 1 : 2,
        JSON.parse(localStorage.getItem("followingObj"))._time
      );
      changeNUM(item);
    }
  });
};

//添加材料后，再次查询接口
const conditionSubmit = () => {
  props.optionInfo.getDetailList(
    props.optionInfo.project,
    props.optionInfo.type === "zhu" ? 1 : 2,
    JSON.parse(localStorage.getItem("followingObj"))._time
  );
  conditionRef.value.clickClose(); //关闭商品选择sku弹窗
};

/**
 * 更改数量之后，前端计算报价（只做展示使用）
 * 如果是条件组合添加的，还要算出 是否超过了限制数量和限制金额
 */
const NUMtotal = ref(0); //数量总和，用来判断是否超过限制数
const isExceedsLimit = ref(false); //是否超出了金额、数量限制
const changeNUM = row => {
  console.log("更改了数量", props.optionInfo.currTempObj);

  if (isAnySelectAny.value) {
    NUMtotal.value = 0; //数量总和，用来判断是否超过限制数
    let numTotal = 0; //“数量”总和
    let otherTotal = 0; //除去当前row之外的“数量”总和
    tableData.value.map(item => {
      numTotal += Number(item.productNum);
      if (item.businessSkuId !== row.businessSkuId) {
        otherTotal += Number(item.productNum);
      }
    });
    console.log("数量累加===", numTotal, Number(_detail.value?.productCheckedNum), otherTotal);
    if (numTotal > Number(_detail.value?.productCheckedNum)) {
      //如果输入的数字过大 超过了“限制数量”，则重置当前row的“数量”，使总和等于“限制数量”
      row.productNum = Number(_detail.value?.productCheckedNum) - otherTotal;
    }
    NUMtotal.value = tableData.value.reduce((prev, cur) => {
      return Number(cur.productNum) + Number(prev);
    }, 0);
    if (NUMtotal.value >= Number(_detail.value?.productCheckedNum)) {
      tableData.value.map(item => {
        item.incrProductNum = null;
      });
    }
  }
  nextTick(() => {
    if (props.optionInfo.currTempObj.budgetType === 2) {
      // 套餐
      console.log("套餐");

      if (
        (props.optionInfo.type === "zhu" && _project.value.mainProductShowType === 2) ||
        (props.optionInfo.type === "fu" && _project.value.auxiliaryProductShowType === 2)
      ) {
        // 条件组合
        console.log("套餐组合", tableData.value);
        // 总报价-只计算增项的（条件外的） isContOut === 1
        let price = 0;
        let limitPrice = 0; //更改数量后的限制金额（非增项的数量*报价）
        let limitNum = 0; //更改数量后的限制数量（增项的数量之和）
        tableData.value.map(item => {
          if (item.isContOut === 1) {
            // 增项
            price += Number(item.productNum) * Number(item.quoteUnitPrice);
          } else {
            //非增项
            limitPrice += Number(item.productNum) * Number(item.quoteUnitPrice);
            limitNum += Number(item.productNum);
          }
        });
        if (limitPrice > _detail.value.limitProductMoney || limitNum > _detail.value.limitProductNum) {
          isExceedsLimit.value = true; //是否超出了金额、数量限制
        } else {
          isExceedsLimit.value = false; //是否超出了金额、数量限制
        }
        _detail.value.quoteMoney = price;
      } else {
        // 固定商品
        console.log("套餐固定商品");
        let price = 0;
        tableData.value.map(item => {
          price += (Number(item.productNum) - Number(item._productNum)) * Number(item.quoteUnitPrice);
        });
        _detail.value.quoteMoney = price;
      }
    } else {
      console.log("清单");
      // 清单
      // 商品添加、条件组合都是所有商品价格累加
      let price = 0;
      tableData.value.map(item => {
        price += Number(item.productNum) * Number(item.quoteUnitPrice);
      });
      _detail.value.quoteMoney = price;
      console.log("AAAAAAAAAAA", tableData.value, price);

      if (
        (props.optionInfo.type === "zhu" && _project.value.mainProductShowType === 2) ||
        (props.optionInfo.type === "fu" && _project.value.auxiliaryProductShowType === 2)
      ) {
        //清单组合条件
        let limitPrice = 0; //更改数量后的限制金额（非增项的数量*报价）
        let limitNum = 0; //更改数量后的限制数量（增项的数量之和）
        tableData.value.map(item => {
          if (item.isContOut === 1) {
            // 增项
          } else {
            //非增项
            limitPrice += Number(item.productNum) * Number(item.quoteUnitPrice);
            limitNum += Number(item.productNum);
          }
        });
        if (limitPrice > _detail.value.limitProductMoney || limitNum > _detail.value.limitProductNum) {
          isExceedsLimit.value = true; //是否超出了金额、数量限制
        } else {
          isExceedsLimit.value = false; //是否超出了金额、数量限制
        }
      }
    }
  });
};

const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

const cancelClick = () => {
  conditionRef.value.reset(true); //清空已选中的sku
  multipleSelection.value = []; //清空table勾选的数据
  _isOpen.value = false;
  // emit("changeAttr");
};
const confirmClick = () => {
  saveLoading.value = true;
  if (
    (props.optionInfo.type === "zhu" && _project.value.mainProductShowType === 2) ||
    (props.optionInfo.type === "fu" && _project.value.auxiliaryProductShowType === 2)
  ) {
    // 根据条件组合添加
    if (isExceedsLimit.value) {
      saveLoading.value = false;
      return ElMessage({
        message: "超出了限制数量或者限制金额，请重新更改数量!",
        type: "error"
      });
    }
    tableData.value.map(item => {
      delete item._productNum;
      item.productNum = Number(item.productNum);
    });
    saveAddition({
      // contentId: _detail.value.contentId,
      productInfos: tableData.value
    })
      .then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "保存成功",
            type: "success"
          });
          conditionRef.value.reset(true); //清空已选中的sku
          _isOpen.value = false;
          emit("submitOk");
        }
      })
      .finally(() => {
        saveLoading.value = false;
      });
  } else {
    /**允许显示几选几的时候，判断勾选的行是否超过允许勾选的数量 */
    // if (
    //   _project.value.quotaType === 7 ||
    //   (_project.value.showSign === 0 &&
    //     _project.value.quotaType === 1 &&
    //     ((props.optionInfo.type === "zhu" && _project.value?.mainProductShowType === 1) ||
    //       (props.optionInfo.type === "fu" && _project.value?.auxiliaryProductShowType === 1)))
    // ) {
    //   if (
    //     multipleSelection.value.length > 0 &&
    //     (productCheckedNum.value === null || multipleSelection.value.length > productCheckedNum.value)
    //   ) {
    //     saveLoading.value = false;
    //     return ElMessage({
    //       message: "超过了允许勾选的数量",
    //       type: "error"
    //     });
    //   }
    // }

    let params = {
      contentId: _detail.value.contentId,
      productInfos: tableData.value,
      productType: props.optionInfo.type === "zhu" ? 1 : props.optionInfo.type === "fu" ? 2 : null
    };

    /**table允许勾选，选中的行checked = 1，未选中的行checked = 0 */
    if (isAllowTableSelect.value) {
      const checkedBusinessSkuIdArr = multipleSelection.value.map(item => item.businessSkuId);
      params.productInfos.map(item => {
        if (checkedBusinessSkuIdArr.includes(item.businessSkuId)) {
          item.checked = 1;
        } else {
          item.checked = 0;
        }
      });
    }
    /**几选几数量 */
    if (isAnySelectAny.value) {
      params.productInfos.map(item => {
        if (item.productNum && Number(item.productNum) > 0) {
          item.checked = 1;
        }
      });
    }

    // console.log("参数===", params);
    // return;
    // 根据商品添加
    updateQuoteProductNum(params)
      .then(res => {
        if (res.code === 200) {
          ElMessage({
            message: "保存成功",
            type: "success"
          });
          _isOpen.value = false;
          emit("submitOk");
        }
      })
      .finally(() => {
        saveLoading.value = false;
      });
  }
};

const spanMethod = ({
  row, // 行
  column, // 列
  rowIndex, // 行索引
  columnIndex // 列索引
}) => {
  if (columnIndex === 8) {
    return setTableRowCol(row, rowIndex, ["xianzhiNum"]);
  }
};

/**
 * 合并行
 * @param {*} row
 * @param {*} rowIndex
 * @param {*} keys
 */
const setTableRowCol = (row, rowIndex, keys) => {
  let firstIndex = 0,
    rowspan = 1,
    colspan = 1;
  // 找到需要合并的行的下标
  firstIndex = tableData.value.findIndex(item => {
    return filterSameKeys(item, row, keys);
  });
  if (rowIndex === firstIndex) {
    // 需要合并的行数
    rowspan = tableData.value.filter(item => {
      return filterSameKeys(item, row, keys);
    }).length;
    colspan = 1;
  } else {
    // 被合并的行需要设置成0
    rowspan = 0;
    colspan = 0;
  }
  return {
    rowspan,
    colspan
  };
};
// 根据keys数组所有字段去做合并
const filterSameKeys = (item, row, keys) => {
  const _item = JSON.parse(JSON.stringify(item));
  let flag = true;
  keys.forEach(key => {
    flag = flag && _item[key] === row[key];
  });
  return flag;
};

defineExpose({});
</script>

<style lang="scss">
.cailiao-dialog {
  .el-dialog {
    padding-left: 0 !important;
    padding-right: 0 !important;
    padding-bottom: 0 !important;
    .el-dialog__header {
      border-bottom: 1px solid #e2e8f0;
      padding: 0 24px 20px 24px;
    }
    .el-dialog__body {
      padding: 20px;
      header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 14px;
        h3 {
          font-size: 16px;
          font-weight: normal;
          color: #3d3d3d;
          span {
            color: #ff3333;
          }
        }
        .left {
          display: flex;
          align-items: center;
          .el-form-item {
            margin-bottom: 0;
          }
        }
      }
    }
    .el-dialog__footer {
      padding-top: 0;
    }
  }
  .dialog-footer {
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    margin: 0;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    display: flex;
    justify-content: space-between;
    .white-input {
      .el-input__wrapper {
        background-color: white !important;
      }
    }
    .left {
      display: flex;
      p {
        display: flex;
        align-items: center;
        span {
          // width: 40px;
          display: inline-block;
          text-align: left;
          & > i.star {
            font-style: normal;
            color: #ff3333;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.el-button--primary {
  --el-button-bg-color: #424e66;
  border: none;
}
.el-button.el-button--info {
  --el-color-info: #f2f3f5;
  --el-color-white: #1d2129;
  &:hover {
    --el-button-hover-bg-color: #f2f3f5 !important;
    border-color: #f2f3f5 !important;
  }
}
</style>
